import { createContext, useContext, FC, useState } from "react";
import { UserProps, UserFromProps } from 'type/user';
import * as auth from "utils/auth-provider";
import { http } from "utils/http";
import { useMount, useAsync } from "utils";
import styled from "styled-components";

const AuthContent = createContext<{
  user: UserProps | null;
  login: (params: UserFromProps) => Promise<void>;
  register: (params: UserFromProps) => Promise<void>;
  logout: () => Promise<void>;
} | undefined>(undefined);
AuthContent.displayName = "AuthContent";

const bootstrapUser = async () => {
  let user: UserProps | null = null;
  const token = auth.getToken();
  if (token) {
    user = await http('me', { token });
  }
  return user;
}

export const AuthProvider: FC = ({ children }) => {
  const { run, isLoading, data: user, setData: setUser } = useAsync<UserProps>();
  const login = (params: UserFromProps) => auth.login(params).then(res => setUser(res.data));
  const register = (params: UserFromProps) => auth.register(params).then(res => setUser(res.data));
  const logout = () => auth.logout().then(() => setUser(null));

  // 初始化登录状态
  useMount(() => {
    run(bootstrapUser());
  });

  if (isLoading) {
    return (
      <FullPage style={{ color: 'red' }}>加载中...</FullPage>
    );
  }
  return (
    <AuthContent.Provider
      value={{
        user,
        login,
        register,
        logout,
      }}
      children={children}
    />
  );
};

export const useAuth = () => {
  const content = useContext(AuthContent);
  if (!content) throw new Error("需要在AuthProvider中使用");
  return content;
};

const FullPage = styled.div`
  height: 100vh;
  display: flex;
  justify-content: center;
`;